#coding=utf-8
import pandas as pd
import matplotlib.pyplot as plt
import re
import numpy as np

#统计系统访问频次【早中晚时间段、按日、按月份访问】
#刷题榜、积分榜、正确率榜
transaction = pd.read_csv('junyi_data/transaction_inited.csv')
#清洗残缺数据
transaction = transaction.dropna(axis=0)


#做题习惯，按时段统计
def count_specific_time():
    specific_time = {'上午':0,'下午':0,'晚上':0}
    loi = transaction['具体时间'].to_numpy()#妙用 解决1404
    for i in range(len(loi)):
        hour = loi[i]
        if 6 <= hour < 12:
            specific_time['上午'] +=1
        elif 12 <= hour < 18:
            specific_time['下午'] += 1
        else:
            specific_time['晚上'] += 1
    specific_time = pd.DataFrame({'具体时段': specific_time})
    specific_time.to_csv('junyi_data/specific_time.csv')

#查看做题是星期几
def get_week_day(date,lop):
    week_day_dict = {
        0: '星期一',
        1: '星期二',
        2: '星期三',
        3: '星期四',
        4: '星期五',
        5: '星期六',
        6: '星期天'
    }
    day = date.weekday()
    lop[week_day_dict[day]] +=1

#做题习惯,按星期几统计
def count_weekday():
    WEEK_DAY = {'星期一':0,'星期二':0,'星期三':0,'星期四':0,'星期五':0,'星期六':0,'星期天':0}
    time = transaction['时间']
    time = pd.to_datetime(time)
    time = list(time)#妙用 解决1404

    for i in range(len(time)):
        get_week_day(time[i],WEEK_DAY)
    WEEK_DAY = pd.DataFrame({'星期几': WEEK_DAY})
    WEEK_DAY.to_csv('junyi_data/weekday_count.csv')

def draw_specific_time_pie():
    # 学生做题习惯,饼图
    specific_time = pd.read_csv('junyi_data/specific_time.csv')
    plt.figure(figsize=(8, 8))
    labels = list(specific_time.iloc[:, 0])
    print(labels)
    data = list(specific_time.iloc[:, 1])
    print(data)
    plt.pie(data, labels=labels, autopct='%.2d%%')
    plt.savefig('static/assets/img/学生做题时间段统计.jpg')
    plt.show()

def draw_weekday_count_line():
    # 学生做题习惯，折线
    weekday_count = pd.read_csv('junyi_data/weekday_count.csv')
    plt.figure(figsize=(8, 8))
    x = list(weekday_count.iloc[:,0])
    y = list(weekday_count.iloc[:,1])
    plt.ylabel('刷题频次')
    plt.plot(x,y)
    plt.savefig('static/assets/img/学生做题星期几统计.jpg')
    plt.show()


def recent_record_count(transaction=transaction,student_id=172560):
    # 最近刷题记录，折线图
    transaction = transaction[transaction['学号'] == 172560]
    print(transaction.head())
    df = transaction.sort_values(by='时间', ascending=False)
    print(df.head())
    date = []
    loi = list(df['时间'])
    for i in range(len(loi)):
        day = re.findall('(.*?) ', loi[i])[0]
        # print(day)
        date.append(day)
    dataframe = pd.DataFrame({'时间': date})
    dataframe = dataframe['时间'].value_counts()
    # print(dataframe.head())
    dataframe.sort_index(
        ascending=False,
        inplace=True,
        axis=0,
        key=None
    )
    print(dataframe)
    dataframe.to_csv('junyi_data/recent_record.csv')

def draw_recent_record_line():
    # 最近刷题记录，折线图
    recent_record = pd.read_csv('junyi_data/recent_record.csv')
    plt.figure(figsize=(8, 8))
    x = list(recent_record.iloc[:5,0])
    y = list(recent_record.iloc[:5,1])
    x.reverse()
    y.reverse()
    print(x,y)
    plt.ylabel('刷题频次')
    plt.xlabel('时间')
    plt.plot(x,y)
    plt.title('学生近期刷题统计')
    # plt.savefig('static/assets/img/学号172560近期刷题统计.jpg')
    plt.show()

plt.rcParams['font.sans-serif'] = [u'simHei']
plt.rcParams['axes.unicode_minus'] = False

if __name__ == '__main__':
    pass



